<?php

if (!function_exists('is_fpm_mode')) {
    /**
     * 是否运行在fpm模式下
     * 
     * @return bool
     */
    function is_fpm_mode()
    {
        return substr(php_sapi_name(), 0, 3) == 'fpm';
    }
}

if (!function_exists('output')) {
    /**
     * 数据格式化
     *
     * @param  mixed   $data
     * @param  int     $code
     * @param  string  $msg
     * @param  array   $args
     * @return array
     *
     */
    function output($data, $code = 0, $msg = '', $args = [])
    {
        $ret = [
            'code' => $code,
            'msg' => $msg == '' ? __('code.' . $code, $args) : $msg,
            'data' => $data,
        ];
        if (env('APP_DEBUG') == true) {
            $ret['sql_log'] = \Illuminate\Support\Facades\DB::getQueryLog();
            \Illuminate\Support\Facades\DB::flushQueryLog();
        }
        if ($ret['data'] === '') unset($ret['data']);
        return $ret;
    }
}

if (!function_exists('error_exit')) {
    /**
     * 自定义错误
     *
     * @param  int            $code
     * @param  string|array   $data
     *
     */
    function error_exit($code, $data = '', $extends = [])
    {
        throw new \App\Exceptions\CustomException($code, $data, $extends);
    }
}

if (!function_exists('custom_resp')) {
    /**
     * 返回自定义响应
     *
     * @param  mixed   $data
     * @param  int     $status
     *
     */
    function custom_resp($data, $status = 200)
    {
        throw new \App\Exceptions\CustomException($status, $data, [], true);
    }
}

if (!function_exists('salt')) {
    /**
     * 产生不重复的随机数
     *
     * @param int $len
     * @return bool|string
     */
    function salt($len = 6)
    {
        $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $string = str_shuffle($string);

        return substr($string, 0, $len);
    }
}

if (!function_exists('password_encrypt')) {
    function password_encrypt($password, $salt)
    {
        return md5(md5($password) . $salt);
    }
}

if (!function_exists('get_page_data')) {
    /**
     * @param Illuminate\Database\Query\Builder $query
     * @param int $page
     * @param int $size
     * @return array
     */
    function get_page_data($query, $page = 1, $size = 20)
    {
        // 兼容DB，Model模式
        if (method_exists($query, 'getQuery')) {
            $columns = $query->getQuery()->columns;
        } else {
            $columns = $query->columns;
        }
        // 兼容自定义groupBy字段问题
        if (empty($columns)) {
            $columns = [Illuminate\Support\Facades\DB::raw("SQL_CALC_FOUND_ROWS *")];
        } else {
            $raw = sprintf('SQL_CALC_FOUND_ROWS %s', $columns[0]);
            $columns[0] = Illuminate\Support\Facades\DB::raw($raw);
        }
        $query->select($columns);

        $page = $page < 1 ? 1 : $page;
        $size = $size < 0 ? 20 : $size;

        $data = $query->offset(($page - 1) * $size)
            ->limit($size)
            ->get()
            ->toArray();

        $total = Illuminate\Support\Facades\DB::select('SELECT FOUND_ROWS() as total')[0]->total;
        return [
            'pagination' => [
                'page' => (int)$page,
                'size' => (int)$size,
                'total' => $total,
            ],
            'list' => $data
        ];
    }
}

if (!function_exists('amount_format_array')) {
    /**
     * 批量金额格式转换 12345 => 12.35  12.35 => 12350
     * @param array $arr   需转换的金额数组
     * @param array $keys  需转换的键，为空则转换全部键
     * @param bool  $float 是否浮点数
     * @return array
     */
    function amount_format_array(&$arr, $keys = [], $float = false)
    {
        if (empty($arr)) {
            return $arr;
        }
        // 只处理数组
        if (is_array($arr)) {
            foreach ($arr as $k => &$v) {
                if (is_array($v)) {
                    amount_format_array($v, $keys, $float);
                } else {
                    if (empty($keys) || in_array($k, $keys)) {
                        $arr[$k] = amount_format($v, $float);
                    }
                }
            }
        }
        return $arr;
    }
}

if (!function_exists('amount_format')) {
    /**
     * 金额格式转换 12345 => 12.34  12.35 => 12350
     * @param int|float $value 需转换的金额
     * @param bool      $float 是否浮点数
     * @return float|int
     */
    function amount_format($value, $float = false)
    {
        if (empty($value)) {
            return 0;
        }
        if (!is_numeric($value)) {
            return $value;
        }
        return $float ? intval(round($value * 1000)) : number_format(floor($value / 10) / 100, 2, '.', '');//输出金额格式化为两位小数
    }
}

if (!function_exists('uniqueCode')) {
    /**
     * 生成唯一值
     */
    function uniqueCode()
    {
        return md5(microtime(true));
    }
}

if (!function_exists('request')) {
    /**
     * 第三方 api http 请求
     * @param string $url 请求地址
     * @param string $method 请求api的方法，get，post，patch 等
     * @param array  $data 数据，body数据，param 数据等
     * @param array  $header 头部信息
     * @param bool   $json 请求数据是否为json串
     * @param array  $options 额外的请求选项 https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html
     * @return Psr\Http\Message\ResponseInterface $response
     */
    function request($url, $method, $data = [], $header = [], $json = true, $options = [])
    {
        $client = new GuzzleHttp\Client();
        $options = ['verify' => false];
        $method = strtoupper($method);
        if (!empty($data)) {
            if ($method === 'GET') {
                $key = 'query';
            } elseif ($json) {
                $key = 'json';
            } else {
                $key = 'form_params';
            }
            $options[$key] = $data;
        }

        if (!empty($header)) {
            $options['headers'] = $header;
        }

        try {
            return $client->request($method, $url, $options);
        } catch (GuzzleHttp\Exception\RequestException $e) {
            if (!$e->hasResponse()) {
                error_exit(500, $e->getMessage());
            }
            return $e->getResponse();
        }
    }
}

if (!function_exists('build_relation_array')) {
    /**
     * 格式化数组为某个字段作为key的关联数组-处理列表二维数组用（用于控制器拼装数据, 避免嵌套循环）
     * @param $array
     * @param $field
     * @return array
     */
    function build_relation_array($array, $field)
    {
        if (empty($array) || empty($field)) {
            return array();
        }

        $returnList = array();
        foreach ($array as $key => $value) {
            if (isset($value[$field]) && $value[$field]) {
                $returnList[$value[$field]] = $value;
            }
        }

        return $returnList;
    }
}

if (!function_exists('recharge_trade_no')) {
    /**
     * 获取充值订单号
     * @param string $preFix 允许自定义顶大好前缀
     * @return string
     */
    function recharge_trade_no($preFix = '')
    {
        return (string)$preFix . date("YmdHis") . rand(pow(10, 3), pow(10, 4) - 1);
    }
}

if (!function_exists('getClientIp')) {
    /**
     * 获取客户端IP
     * @return string 返回ip地址,如127.0.0.1
     */
    function getClientIp()
    {
        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            return $_SERVER['HTTP_X_REAL_IP'];
        }

        $onlineip = 'Unknown';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
            $real_ip = $ips['0'];
            if ($_SERVER['HTTP_X_FORWARDED_FOR'] && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $real_ip)) {
                $onlineip = $real_ip;
            } elseif ($_SERVER['HTTP_CLIENT_IP'] && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
                $onlineip = $_SERVER['HTTP_CLIENT_IP'];
            }
        }
        if ($onlineip == 'Unknown' && isset($_SERVER['HTTP_CDN_SRC_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CDN_SRC_IP'])) {
            $onlineip = $_SERVER['HTTP_CDN_SRC_IP'];
        }
        if ($onlineip == 'Unknown' && isset($_SERVER['HTTP_NS_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_NS_IP'])) {
            $onlineip = $_SERVER['HTTP_NS_IP'];
        }
        if ($onlineip == 'Unknown' && isset($_SERVER['REMOTE_ADDR']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['REMOTE_ADDR'])) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }

        return $onlineip;
    }
}

if (!function_exists('generate_order_number')) {
    /**
     * 获取系统通用订单号
     * @param string $preFix 允许自定义顶大好前缀
     * @return string
     */
    function generate_order_number($subfix = '')
    {
        list($t1, $t2) = explode(' ', microtime());
        $mTime = (float)sprintf('%.0f', floatval($t1) * 10000);
        return date('Ymdhis') . mt_rand(1000, 9999) . $mTime . $subfix;
    }
}